package com.msblearn.C_005;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * T10_ReentrantLock:可重入锁
 * reentrantlock是可以被打断的。
 * 使用lockInterrruptibly()方法
 */
public class T01_ReentrantLock4 {

    public static void main(String[] args) throws InterruptedException {
        Lock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {

            try {
                lock.lock();
                System.out.println("t1 start!");
                TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("thread interrupt!!!!");
            } finally {
                lock.unlock();
            }

        });
        t1.start();

        Thread t2 = new Thread(() -> {
            try {
//               lock.lock();
                lock.lockInterruptibly();
                System.out.println("t2 start!");
                TimeUnit.SECONDS.sleep(5);
                System.out.println("t2 end!");
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("thread interrupt!!!!");
            } finally {
                lock.unlock();
            }
        });
        t2.start();
        //打断锁。
        TimeUnit.SECONDS.sleep(1);
        t2.interrupt();
    }
}
